#!/usr/bin/env python
# encoding: utf-8


from app.views.api import route_api
from  flask import request,jsonify
import json

from app import db
from app.model import User
from app.model import Electronic
from app.model import ElectronicInLog
from app.model import ElectronicInOrder
from app.model import ElectronicInOrderItem

from app.common.libs.Logging import logger
from app.common.libs.Helper import getCurrentDate, getFormatDate
from app.common.libs.UserService import UserService

from app.common.libs.electronic.InOrderService import InOrderService

@route_api.route("/electronic/in/order/create",methods = [ "GET","POST" ])
def inOrderAdd():
    resp = { 'code':20000,'message':'入库订单创建成功~', 'data':{}}
    req = request.values
    electronics = req['electronics'] if 'electronics' in req else None
    items = []
    if electronics:
        items = json.loads(electronics)

    if len( items ) < 1:
        resp['code'] = -1
        resp['message'] = "下单失败：未选择元器件~~"
        return jsonify(resp)

    user_info = UserService.getUserInfo(request)
    if not user_info :
        resp['code'] = -1
        resp['message'] = "下单失败：用户未登录~~"
        return jsonify(resp)

    note = req['note'] if 'note' in req else ''

    target = InOrderService()
    resp = target.createOrder(user_info.id, items, note)

    return jsonify( resp )

@route_api.route("/electronic/in/order/list",methods = [ "GET","POST" ])
def inOrderList():
    resp = { 'code':20000,'message':'出库订单查询成功~', 'data':{}}

    user_info = UserService.getUserInfo(request)
    roles = user_info.roles.split(';')

    if "库管" in roles:
        order_list = db.session.query(User.nickname,
                                ElectronicInOrder.order_sn,
                                ElectronicInOrder.status,
                                ElectronicInOrder.created_time,
                                ElectronicInOrder.note
                                )\
                                .filter( ElectronicInOrder.user_id == User.id )\
                                .all()
    else:
        order_list = db.session.query(User.nickname,
                                  ElectronicInOrder.order_sn,
                                  ElectronicInOrder.status,
                                  ElectronicInOrder.created_time,
                                  ElectronicInOrder.note
                                  )\
                                .filter( User.id == user_info.id )\
                                .filter( ElectronicInOrder.user_id == User.id )\
                                .all()

    data = []
    for item in order_list:
        status = ''
        if item[2]==0:
            status = '订单无效'
        elif item[2]==1:
            status = '待入库'
        elif item[2]==2:
            status = '已入库'
        data.append({
            'user': item[0],
            'sn': item[1],
            'status': status,
            'created_time': getFormatDate(item[3]),
            'note': item[4],
        })
    resp['data'] = data

    return jsonify( resp )


@route_api.route("/electronic/in/order/info",methods = [ "GET","POST" ])
def inOrderInfo():
    resp = { 'code':20000,'message':'出库订单查询成功~', 'data':{}}
    req = request.values
    sn = req['sn'] if 'sn' in req else ''

    user_info = UserService.getUserInfo(request)

    order_item_list = db.session.query(
                                    Electronic.name,
                                    Electronic.sn,
                                    Electronic.position,
                                    ElectronicInOrderItem.count,
                                    ElectronicInOrderItem.status,
                                    ElectronicInOrderItem.note)\
                                    .filter( ElectronicInOrderItem.electronic_in_order_id == ElectronicInOrder.id )\
                                    .filter( ElectronicInOrderItem.electronic_id == Electronic.id )\
                                    .filter( ElectronicInOrder.order_sn == sn )\
                                    .all()
    data = []
    for item in order_item_list:
        status = ''
        if item[4]==0:
            status = '成功'
        elif item[4]==1:
            status = '失败'
        data.append({
            'electronic_name': item[0],
            'electronic_sn': item[1],
            'electronic_position': item[2],
            'count': item[3],
            'status': status,
            'note': item[5],
            })
    resp['data'] = data

    return jsonify( resp )

@route_api.route("/electronic/in/order/delete",methods = [ "GET","POST" ])
def inOrderDelete():
    resp = { 'code':20000,'message':'出库订单删除成功~', 'data':{}}
    return jsonify( resp )

@route_api.route("/electronic/in/order/instock",methods = [ "GET","POST" ])
def inOrderInStock():
    resp = { 'code':20000,'message':'元器件入库成功~', 'data':{}}
    req = request.values
    sn = req['sn'] if 'sn' in req else ''

    order_info = db.session.query(ElectronicInOrder).filter_by(order_sn = sn).first()
    if order_info.status == 2:
        resp['code'] = -1
        resp['message'] = "出库失败，当前订单已经入库，无需重复入库~~"
        return jsonify(resp)

    user_info = UserService.getUserInfo(request)

    order_item_list = db.session.query(ElectronicInOrderItem)\
                                    .filter( ElectronicInOrderItem.electronic_in_order_id == ElectronicInOrder.id )\
                                    .filter( ElectronicInOrder.id== order_info.id )\
                                    .all()
    # 获取入库列表中的元器件id列表
    electronic_ids = []
    for item in order_item_list:
        electronic_ids.append( item.electronic_id)

    try:
        #为了防止并发库存出问题了，根据元器件id列表，选用with_for_update
        electronic_list = db.session.query( Electronic ).filter( Electronic.id.in_( electronic_ids ) )\
            .with_for_update().all()

        # 库存映射
        electrionic_stock_mapping = {}
        for item in electronic_list:
            electrionic_stock_mapping[ item.id ] = item.stock

        for item in order_item_list:
            # 修改库存数量
            left_stock =  electrionic_stock_mapping[ item.electronic_id ]
            ret = Electronic.query.filter_by( id = item.electronic_id ).update({
                "stock":int(left_stock) + int(item.count)
            })
            if not ret:
                raise Exception("入库失败，请重新出库")

            # 添加入库记录
            in_stock_model = ElectronicInLog()
            in_stock_model.user_id = user_info.id
            in_stock_model.electronic_id = item.electronic_id
            in_stock_model.count = item.count
            in_stock_model.note = "完成入库"
            in_stock_model.created_time = getCurrentDate()
            db.session.add(in_stock_model)
        # 更新订单中出库时间
        order_info.status = 2
        order_info.in_time = getCurrentDate()
        db.session.commit()
    except Exception as e:
        print(e)
        db.session.rollback()
        resp['code'] = -1
        resp['message'] = "入库失败请重新入库"
    return jsonify( resp )

